package com.qidian.buy.controller;

import com.google.gson.Gson;
import com.qidian.buy.util.pojo.QdResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2023/9/6 15:16
 */
@RestController
public class UploadController {

    @Value("${accessKey}")
    private String accessKey;
    @Value("${secretKey}")
    private String secretKey;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${imageServerPath}")
    private String imageServerPath;


    @PostMapping("/wangUpload")
    public Map wangUpload(@RequestParam(value = "uploadFile")MultipartFile uploadFile) throws IOException {
        Map result = new HashMap();
        String originalFilename = uploadFile.getOriginalFilename();
        // 获取文件的后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成文件名
        String fileName = UUID.randomUUID().toString().replace("-","") + ext;
        // 准备上传
        InputStream in = uploadFile.getInputStream();
        // 认证
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucketName);

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        // 开始上传
        try {
            Response response = uploadManager.put(in,fileName,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
            // 响应客户端  msg是图片的完整的访问地址
            result.put("errno",0);
            Map data = new HashMap();
            data.put("url",imageServerPath + fileName);
            result.put("data",data);
            return result;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        result.put("errno",1);
        result.put("message","上传失败");
        return result;
    }

    @PostMapping("/upload")
    public QdResult upload(@RequestParam(value = "uploadFile")MultipartFile uploadFile) throws IOException {
        String originalFilename = uploadFile.getOriginalFilename();
        // 获取文件的后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成文件名
        String fileName = UUID.randomUUID().toString().replace("-","") + ext;
        // 准备上传
        InputStream in = uploadFile.getInputStream();
        // 认证
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucketName);

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        // 开始上传
        try {
            Response response = uploadManager.put(in,fileName,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
            // 响应客户端  msg是图片的完整的访问地址
            return QdResult.ok(imageServerPath + fileName);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        return QdResult.fail();
    }

}
